<template>
  <div>
    <div class="login-container">
      <div class="head">
        <div class="loginLogoBox">
          <img class="loginLogo" src="@/static/loginLogo.png" alt="" />
        </div>
        <div class="line"></div>
        <span>管理中台</span>
      </div>
      <div class="centerBj">
        <img class="loginCenter" src="@/static/loginCenter.png" alt="">
        <div class="loginFormBox">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <div class="title-container">
            <h3 class="title">用户登录 USERLOGIN</h3>
          </div>

          <el-form-item prop="userName">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="userName"
              v-model="loginForm.userName"
              placeholder="用户名"
              name="userName"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>

          <el-tooltip
            v-model="capsTooltip"
            content="已锁定大写字母"
            placement="right"
            manual
          >
            <el-form-item prop="password">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>
          </el-tooltip>

          <el-form-item prop="code">
            <captcha-input v-model="loginForm.code" @getCodeKey="_getCodeKey" />
          </el-form-item>

          <el-button
            :loading="loading"
            type="primary"
            style="width: 100%; margin:18px 0 30px;height: 46px"
            @click.native.prevent="handleLogin"
            >登录</el-button
          >
        </el-form>
      </div>
      </div>
      <div class="bottomtxt">©2020 All Rights Reserved 海南炎煌纵横科技有限公司 琼ICP备2020005082号-1</div>
    
    </div>
    <Dialog
      v-bind="$attrs"
      v-if="dialogVisible"
      :loginForm="loginForm"
      :visible.sync="dialogVisible"
      @success="_handleSuccess"
    >
    </Dialog>
  </div>
  
</template>

<script>
import { validUsername } from "@/utils/validate";

import CaptchaInput from "@/components/CaptchaInput/index";

import Dialog from "./components/dialog";

import { rsaEncrypt } from '@/utils/RSA.js'


export default {
  name: "Login",
  components: {
    Dialog,
    CaptchaInput,
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("密码必须是至少六位数的字符"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      loginForm: {
        userName: process.env.NODE_ENV === "development" ? "admin" : "",
        password: process.env.NODE_ENV === "development" ? "admin" : "",
        code: "",
        uuid: "",
      },
      loginRules: {
        userName: [
          { required: true, message: "请输入正确的用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      isKeyboard:false, //限制重复提交登录
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    const that = this;
    // if (this.loginForm.userName === '') {
    //   this.$refs.userName.focus()
    // } else if (this.loginForm.password === '') {
    //   this.$refs.password.focus()
    // }

    // 添加键盘事件, 点击回车键登录
    window.addEventListener("keydown", this.handleLogin, true);
    this.$once("hook:destroyed", () => {
      console.log("destroyeddestroyed");
      window.removeEventListener("keydown", this.handleLogin, true);
    });
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    // 检查大写字母是否锁定
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },

    // 显示密码明文
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },

    // 获取验证码KEY值
    _getCodeKey(value) {
      this.loginForm.uuid = value;
    },

    handleLogin() {
      if (event.keyCode && event.keyCode !== 13) return;
      if(this.isKeyboard==true){
        return
      }
      this.$refs.loginForm.validate((valid) => {
        console.log(5555555555555555555);
        if (valid) {
          if (/Mobi|Android|iPhone/i.test(navigator.userAgent)) { // 当前设备是否移动设备
            this.$message.warning('请使用PC电脑操作!')
            return
          }
          this.isKeyboard=true
          this.loading = true;
          let jiami = rsaEncrypt(JSON.stringify(this.loginForm)) //rsa加密
					let params = {
						encryptData: jiami
					}
          this.$store
            .dispatch("user/login", params)
            .then((res) => {
              this.isKeyboard=false
              this.loading = false;
              console.log(123123,res);
              console.log('this.loading',this.loading)
              if(res.type == 1){
                this.$router.push({
                  path: "/",
                  query: this.otherQuery,
                });
                
              }else if(res.type == 2){
                this.dialogVisible = true
              }
              
            })
            .catch(() => {
              this.isKeyboard=false
              this.loading = false;
            });
            
        }
      });
    },
    _handleSuccess(){

    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
  },
};
</script>

<style lang="scss" scoped>
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #F6F8FB;
$light_gray: #303133;
$cursor: #303133;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}
/* reset element-ui css */
.login-container {
  ::v-deep .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px !important;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    // background: rgba(0, 0, 0, 0.1);
    // border-radius: 5px;
    // color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #f6f8fb;
$dark_gray: #889aa4;
$light_gray: #eee;
.el-button--primary {
    color: #FFFFFF;
    background-color: #FF9300;
    border-color: #FF9300;
}
.el-button--primary:hover{
  opacity: 0.8;
}
.login-container .el-form-item{
  background-color: #F6F8FB;
}
.loginFormBox {
  background-color: #ccc;
  margin: 0 auto;
  width: 560px;
  height: 450px;
  max-width: 100%;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 4px 6px 16px 0px rgba(0,0,0,0.08);
  position: relative;
  top: -43px; 
}
.head {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ff9300;
  font-size: 40px;
  margin: 65px 0 113px;
}
.line {
  width: 1px;
  height: 44px;
  background-color: #c0c4cc;
  margin: 0 31px;
}
.loginLogoBox{
  padding-top: 12px;
}
.loginLogo {
  max-width: 190px;
  height: 55px;
}
.centerBj {
  height: 360px;
  width: 100%;
  background: radial-gradient(#ffa730, #ff9300);
  position: relative;
}
.loginCenter{
  position: absolute;
  top: 0;
  z-index: 0;
  height: 100%;
}
.bottomtxt{
  width: 100%;
  display: flex;
  justify-content: center;
  font-size: 16px;
  color: #909399;
  position: fixed;
  bottom: 40px;
}
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    // width: 520px;
    max-width: 100%;
    padding: 40px 60px 0;
    // margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 24px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
      color: #909399;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
